package com.forlove.app.qselect.friend.widget.dialog;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageButton;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.forlove.app.R;
import com.forlove.app.common.utils.SystemUtils;
import com.forlove.app.qselect.answer.presenter.AnswerSubjectPresenter;
import com.forlove.app.qselect.answer.ui.fragment.BaseCandidateFragment;
import com.forlove.app.qselect.answer.ui.fragment.SetAnswerFriendFragment;
import com.forlove.app.qselect.answer.ui.fragment.SetCandidateFragment;
import com.forlove.app.qselect.answer.widght.indicator.TitleTabIndicator;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by yjl on 2017/10/23.
 */

public class SetNewCandidateDialog extends DialogFragment implements View.OnClickListener,
        BaseCandidateFragment.SelectFriendListener {
    private TitleTabIndicator view_tab_indicator;
    private ViewPager view_pager_candidate;
    private AppCompatEditText edittext_input_query;
    private AppCompatImageButton image_cancel_query;
    private ViewAdapter viewAdapter;
    private View rootView;
    private Window mWindow;
    private AnswerSubjectPresenter answerSubjectPresenter;
    private List<BaseCandidateFragment> baseCandidateFragments = new ArrayList<>();
    private SetAnswerFriendFragment setAnswerFriendFragment;
    private SetCandidateFragment setCandidateFragment;
    private int mCurrentPosition = BaseCandidateFragment.position_choice_friend;
    private List<MineFriendEntity> selectFriend = new ArrayList<>();//选择了的候选人好友
    private List<MineFriendEntity> circleFirend = new ArrayList<>();//指定答题的候选人
    private AnswerViewListener answerViewListener;

    public void setPresenter(AnswerSubjectPresenter presenter) {
        this.answerSubjectPresenter = presenter;
        for (BaseCandidateFragment baseCandidateFragment : baseCandidateFragments) {
            baseCandidateFragment.setPresenter(answerSubjectPresenter);
        }
    }

    public void setAnswerViewListener(AnswerViewListener answerViewListener) {
        this.answerViewListener = answerViewListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NORMAL, R.style.DialogCandidateStyle);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.dialog_new_set_candidate, null);
        initDialog();
        initView();
        initQuerySelect();
        return rootView;
    }

    private void initDialog() {
        mWindow = getDialog().getWindow();
        WindowManager.LayoutParams params = mWindow.getAttributes();
        params.gravity = Gravity.BOTTOM | Gravity.CENTER;
        WindowManager windowManager = mWindow.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        params.width = display.getWidth();
        mWindow.setAttributes(params);
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT);
    }

    private void initView() {
        if (baseCandidateFragments == null) {
            baseCandidateFragments = new ArrayList<>();
        }
        view_tab_indicator = rootView.findViewById(R.id.view_tab_indicator);
        view_pager_candidate = rootView.findViewById(R.id.view_pager_candidate);
        if (baseCandidateFragments.size() == 0) {
            baseCandidateFragments.clear();
            setAnswerFriendFragment = new SetAnswerFriendFragment();
            setAnswerFriendFragment.setSelectFriendListener(this);
            setAnswerFriendFragment.setPresenter(answerSubjectPresenter);
            baseCandidateFragments.add(BaseCandidateFragment.position_choice_friend, setAnswerFriendFragment);
            setCandidateFragment = new SetCandidateFragment();
            setCandidateFragment.setSelectFriendListener(this);
            setCandidateFragment.setPresenter(answerSubjectPresenter);
            baseCandidateFragments.add(BaseCandidateFragment.position_set_candidate, setCandidateFragment);
        }

        viewAdapter = new ViewAdapter(getChildFragmentManager());

        view_pager_candidate.setAdapter(viewAdapter);
        view_tab_indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                baseCandidateFragments.get(position).onPageSelect(position);
                mCurrentPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        view_tab_indicator.setViewPager(view_pager_candidate);
    }

    private void initQuerySelect() {
        image_cancel_query = rootView.findViewById(R.id.image_cancel_query);
        image_cancel_query.setOnClickListener(this);
        edittext_input_query = rootView.findViewById(R.id.edittext_input_query);
        edittext_input_query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String queryStr = s.toString().replaceAll(" ", "");
                if (baseCandidateFragments != null
                        && mCurrentPosition < baseCandidateFragments.size()) {
                    baseCandidateFragments.get(mCurrentPosition).inputQuery(queryStr);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_cancel:
                dismiss();
                break;
            case R.id.image_cancel_query:
                cancelQuery();
                break;
        }
    }

    private void cancelQuery() {
        edittext_input_query.setText("");
        SystemUtils.hideKeyBoard(getContext(), image_cancel_query);
        if (baseCandidateFragments != null
                && mCurrentPosition < baseCandidateFragments.size()) {
            baseCandidateFragments.get(mCurrentPosition).cancelQuery();
        }
    }

    public synchronized void setFriendsData(final List<MineFriendEntity> recommendFriend,
                                            final List<MineFriendEntity> qyqFriends,
                                            final List<ContactsInfoEntity> contactsInfoEntities) {
        BaseCandidateFragment.setFriendsData(recommendFriend, qyqFriends, contactsInfoEntities);
    }

    public void clearData() {
        baseCandidateFragments.clear();
        answerSubjectPresenter = null;
        if (setAnswerFriendFragment != null) {
            setAnswerFriendFragment.clearData();
        }
        if (setCandidateFragment != null) {
            setCandidateFragment.clearData();
        }
    }

    private class ViewAdapter extends FragmentPagerAdapter {
        public ViewAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public BaseCandidateFragment getItem(int position) {
            BaseCandidateFragment fragment = (baseCandidateFragments == null
                    || baseCandidateFragments.size() == 0) ? null : baseCandidateFragments.get(position);
            return fragment;
        }

        @Override
        public int getCount() {
            return baseCandidateFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return baseCandidateFragments.get(position).getClass().getSimpleName();
        }

        @Override
        public int getItemPosition(Object object) {
            // 什么都不做
            if (object instanceof SetCandidateFragment) {
                return BaseCandidateFragment.position_choice_friend;
            } else if (object instanceof SetAnswerFriendFragment) {
                return BaseCandidateFragment.position_set_candidate;
            }
            return POSITION_UNCHANGED;
        }
    }


    @Override
    public void selectedFirend(List<MineFriendEntity> mineFriendEntities, int position) {
        //设置候选人
        if (position == BaseCandidateFragment.position_set_candidate) {
            selectFriend.clear();
            selectFriend.addAll(mineFriendEntities);
            if (answerViewListener != null) {
                answerViewListener.updateCandidate(selectFriend);
            }
        } else if (position == BaseCandidateFragment.position_choice_friend) {
            //选择答题人
            circleFirend.clear();
            circleFirend.addAll(mineFriendEntities);
            if (answerViewListener != null) {
                answerViewListener.answerSubject(circleFirend);
            }
        }
    }

    @Override
    public void closeDialog() {
        dismiss();
    }

    /**
     * 获取选择了的好友
     *
     * @return
     */
    public List<MineFriendEntity> getSelectedFriends() {

        return selectFriend;
    }

    public List<MineFriendEntity> getCircleFirend() {
        return circleFirend;
    }

    public interface AnswerViewListener {
        //答题
        void answerSubject(List<MineFriendEntity> circleFirend);

        //更新候选人
        void updateCandidate(List<MineFriendEntity> mineFriendEntities);
    }

    public boolean isShowing() {
        if (getDialog() != null) {
            return getDialog().isShowing();
        }
        return false;
    }

}
